﻿using System;
using System.Drawing;
using System.Windows.Forms;
using FBroSharp;
using FBroSharp.Lib;
using FBroSharp.Value;
using FBroSharp.DataType;

namespace 电商价格监控器
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "jd_monitor_browser";
        private IFBroSharpBrowser _browser;
        private ProductMonitor _monitor;
        private bool _isMonitoring = false;

        public Form1()
        {
            InitializeComponent();
            _monitor = new ProductMonitor();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 初始化界面
            UpdateStatus("初始化中...");

            // 创建浏览器
            CreateBrowser();
        }

        /// <summary>
        /// 创建嵌入式浏览器
        /// </summary>
        private void CreateBrowser()
        {
            try
            {
                // 配置窗口信息（嵌入式浏览器）
                FBroSharpWindowsInfo windowInfo = new FBroSharpWindowsInfo
                {
                    parent_window = panelBrowser.Handle,  // ⚠️ CRITICAL for embedded browser!
                    x = 0,
                    y = 0,
                    width = panelBrowser.Width,
                    height = panelBrowser.Height,
                    window_name = "JD Monitor Browser"
                };

                // 配置浏览器设置
                FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

                // 创建浏览器事件处理器
                BrowserEvent browserEvent = new BrowserEvent(this);

                // 创建浏览器
                bool success = FBroSharpControl.CreatBrowser(
                    txtUrl.Text,
                    windowInfo,
                    settings,
                    null,  // request_context
                    null,  // extra_info
                    browserEvent,
                    default,  // ⚠️ CRITICAL: Use default for struct value type!
                    BROWSER_USER_FLAG
                );

                if (success)
                {
                    UpdateStatus("浏览器创建成功，正在加载页面...");
                }
                else
                {
                    UpdateStatus("浏览器创建失败！");
                    MessageBox.Show("浏览器创建失败！请检查 FBro 框架是否正确初始化。", "错误",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"创建浏览器异常: {ex.Message}");
                MessageBox.Show($"创建浏览器时发生异常:\n{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 浏览器创建完成回调
        /// </summary>
        public void OnBrowserCreated(IFBroSharpBrowser browser)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnBrowserCreated(browser)));
                return;
            }

            _browser = browser;
            UpdateStatus("浏览器已就绪，页面加载中...");
        }

        /// <summary>
        /// 开始监控按钮
        /// </summary>
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrWhiteSpace(txtUrl.Text))
                {
                    MessageBox.Show("请输入商品链接！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 提取 SKU ID
                string skuId = ExtractSkuId(txtUrl.Text);
                if (string.IsNullOrEmpty(skuId))
                {
                    MessageBox.Show("无法从链接中提取商品ID，请确认链接格式正确！\n" +
                                  "示例: https://item.jd.com/100209268309.html",
                        "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 设置监控商品
                _monitor.SetProduct(skuId, txtUrl.Text, lblTitle.Text, txtTargetPrice.Text);
                _monitor.Config.CheckIntervalMinutes = (int)numInterval.Value;
                _monitor.SaveData();

                // 启动定时器
                monitorTimer.Interval = (int)numInterval.Value * 60 * 1000;  // 转换为毫秒
                monitorTimer.Start();
                _isMonitoring = true;

                // 更新按钮状态
                btnStart.Enabled = false;
                btnStop.Enabled = true;

                // 立即执行一次检查
                CheckPrice();

                UpdateStatus($"监控已启动，每 {numInterval.Value} 分钟检查一次");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动监控失败:\n{ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 停止监控按钮
        /// </summary>
        private void btnStop_Click(object sender, EventArgs e)
        {
            StopMonitoring();
        }

        /// <summary>
        /// 停止监控
        /// </summary>
        private void StopMonitoring()
        {
            monitorTimer.Stop();
            _isMonitoring = false;

            btnStart.Enabled = true;
            btnStop.Enabled = false;

            UpdateStatus("监控已停止");
        }

        /// <summary>
        /// 立即检查价格按钮
        /// </summary>
        private void btnCheckNow_Click(object sender, EventArgs e)
        {
            CheckPrice();
        }

        /// <summary>
        /// 通知设置按钮
        /// </summary>
        private void btnSettings_Click(object sender, EventArgs e)
        {
            // 创建通知设置对话框
            using (Form settingsForm = new Form())
            {
                settingsForm.Text = "⚙️ 通知设置";
                settingsForm.Size = new Size(500, 400);
                settingsForm.StartPosition = FormStartPosition.CenterParent;
                settingsForm.FormBorderStyle = FormBorderStyle.FixedDialog;
                settingsForm.MaximizeBox = false;
                settingsForm.MinimizeBox = false;

                // 消息框通知
                CheckBox chkMessageBox = new CheckBox
                {
                    Text = "启用消息框通知",
                    Location = new Point(20, 20),
                    Checked = _monitor.Config.EnableMessageBoxNotification,
                    AutoSize = true
                };

                // 邮件通知
                CheckBox chkEmail = new CheckBox
                {
                    Text = "启用邮件通知",
                    Location = new Point(20, 60),
                    Checked = _monitor.Config.EnableEmailNotification,
                    AutoSize = true
                };

                Label lblSmtp = new Label { Text = "SMTP服务器:", Location = new Point(40, 90), AutoSize = true };
                TextBox txtSmtp = new TextBox { Location = new Point(150, 87), Width = 200, Text = _monitor.Config.Email.SmtpServer };

                Label lblPort = new Label { Text = "端口:", Location = new Point(40, 120), AutoSize = true };
                TextBox txtPort = new TextBox { Location = new Point(150, 117), Width = 100, Text = _monitor.Config.Email.SmtpPort.ToString() };

                Label lblFrom = new Label { Text = "发件人邮箱:", Location = new Point(40, 150), AutoSize = true };
                TextBox txtFrom = new TextBox { Location = new Point(150, 147), Width = 200, Text = _monitor.Config.Email.FromEmail };

                Label lblPass = new Label { Text = "邮箱密码:", Location = new Point(40, 180), AutoSize = true };
                TextBox txtPass = new TextBox { Location = new Point(150, 177), Width = 200, Text = _monitor.Config.Email.FromPassword, UseSystemPasswordChar = true };

                Label lblTo = new Label { Text = "收件人邮箱:", Location = new Point(40, 210), AutoSize = true };
                TextBox txtTo = new TextBox { Location = new Point(150, 207), Width = 200, Text = _monitor.Config.Email.ToEmail };

                // 微信通知
                CheckBox chkWeChat = new CheckBox
                {
                    Text = "启用微信通知（企业微信机器人）",
                    Location = new Point(20, 250),
                    Checked = _monitor.Config.EnableWeChatNotification,
                    AutoSize = true
                };

                Label lblWebhook = new Label { Text = "Webhook URL:", Location = new Point(40, 280), AutoSize = true };
                TextBox txtWebhook = new TextBox { Location = new Point(150, 277), Width = 300, Text = _monitor.Config.WeChatWebhookUrl };

                // 按钮
                Button btnSave = new Button { Text = "保存", Location = new Point(200, 320), Width = 80 };
                Button btnTest = new Button { Text = "测试通知", Location = new Point(300, 320), Width = 80 };

                btnSave.Click += (s, ev) =>
                {
                    _monitor.Config.EnableMessageBoxNotification = chkMessageBox.Checked;
                    _monitor.Config.EnableEmailNotification = chkEmail.Checked;
                    _monitor.Config.Email.SmtpServer = txtSmtp.Text;
                    _monitor.Config.Email.SmtpPort = int.TryParse(txtPort.Text, out int port) ? port : 587;
                    _monitor.Config.Email.FromEmail = txtFrom.Text;
                    _monitor.Config.Email.FromPassword = txtPass.Text;
                    _monitor.Config.Email.ToEmail = txtTo.Text;
                    _monitor.Config.EnableWeChatNotification = chkWeChat.Checked;
                    _monitor.Config.WeChatWebhookUrl = txtWebhook.Text;
                    _monitor.SaveData();

                    MessageBox.Show("设置已保存！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    settingsForm.Close();
                };

                btnTest.Click += (s, ev) =>
                {
                    // 临时应用设置进行测试
                    var tempConfig = new ProductMonitor.MonitorConfig
                    {
                        EnableMessageBoxNotification = chkMessageBox.Checked,
                        EnableEmailNotification = chkEmail.Checked,
                        Email = new ProductMonitor.EmailConfig
                        {
                            SmtpServer = txtSmtp.Text,
                            SmtpPort = int.TryParse(txtPort.Text, out int port) ? port : 587,
                            FromEmail = txtFrom.Text,
                            FromPassword = txtPass.Text,
                            ToEmail = txtTo.Text
                        },
                        EnableWeChatNotification = chkWeChat.Checked,
                        WeChatWebhookUrl = txtWebhook.Text
                    };

                    NotificationHelper.SendTestNotification(tempConfig);
                };

                settingsForm.Controls.AddRange(new Control[] {
                    chkMessageBox, chkEmail, lblSmtp, txtSmtp, lblPort, txtPort,
                    lblFrom, txtFrom, lblPass, txtPass, lblTo, txtTo,
                    chkWeChat, lblWebhook, txtWebhook, btnSave, btnTest
                });

                settingsForm.ShowDialog();
            }
        }

        /// <summary>
        /// 定时器触发
        /// </summary>
        private void monitorTimer_Tick(object sender, EventArgs e)
        {
            CheckPrice();
        }

        /// <summary>
        /// 检查价格
        /// </summary>
        private void CheckPrice()
        {
            try
            {
                if (_browser == null || !_browser.IsValid)
                {
                    UpdateStatus("浏览器未就绪，无法检查价格");
                    return;
                }

                UpdateStatus("正在检查价格...");

                // 导航到商品页面（如果当前不在该页面）
                var frame = _browser.GetMainFrame();
                if (frame != null && frame.GetURL() != txtUrl.Text)
                {
                    frame.LoadURL(txtUrl.Text);
                    
                    // 等待页面加载
                    System.Threading.Thread.Sleep(3000);
                }

                // 执行 JavaScript 获取价格信息
                ExecuteGetPriceScript();
            }
            catch (Exception ex)
            {
                UpdateStatus($"检查价格失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 执行JavaScript获取价格
        /// </summary>
        private void ExecuteGetPriceScript()
        {
            try
            {
                if (_browser == null || !_browser.IsValid)
                    return;

                var frame = _browser.GetMainFrame();
                if (frame == null)
                    return;

                // JavaScript 代码：获取商品信息
                string jsCode = @"
                (function() {
                    // 商品标题
                    var title = document.querySelector('.sku-name')?.innerText || 
                                document.querySelector('.itemInfo-wrap .name')?.innerText || 
                                document.querySelector('h1')?.innerText || 
                                'N/A';
                    
                    // 价格（京东价格动态加载，尝试多个选择器）
                    var priceElement = document.querySelector('.p-price .price') || 
                                       document.querySelector('#jd-price') ||
                                       document.querySelector('.price-point') ||
                                       document.querySelector('.p-price span');
                    var price = priceElement ? priceElement.innerText.trim() : 'N/A';
                    
                    // 库存状态
                    var stockElement = document.querySelector('#stock-state-text') ||
                                       document.querySelector('.stock-txt') ||
                                       document.querySelector('.state') ||
                                       document.querySelector('.stock-prompt');
                    var stock = stockElement ? stockElement.innerText.trim() : '有货';
                    
                    // 返回结果（通过页面标题传递）
                    document.title = 'PRICE_DATA|' + title + '|' + price + '|' + stock;
                    return {title: title, price: price, stock: stock};
                })();
                ";

                // 执行脚本
                frame.ExecuteJavaScript(jsCode, "", 0);

                // 延迟获取结果
                System.Threading.Timer timer = null;
                timer = new System.Threading.Timer(_ =>
                {
                    timer?.Dispose();
                    ProcessPriceData();
                }, null, 2000, System.Threading.Timeout.Infinite);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"执行JS失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 处理价格数据
        /// </summary>
        private void ProcessPriceData()
        {
            try
            {
                if (InvokeRequired)
                {
                    Invoke(new Action(ProcessPriceData));
                    return;
                }

                if (_browser == null || !_browser.IsValid)
                    return;

                var frame = _browser.GetMainFrame();
                if (frame == null)
                    return;

                // 从页面标题读取数据（临时方案）
                string pageTitle = ""; // 注意：FBro 需要通过其他方式获取
                
                // 备选方案：执行 JavaScript 并通过回调获取结果
                // 这里我们直接模拟价格获取（实际项目中需要使用 FBro 的回调机制）
                
                // 简化版本：直接从界面元素读取（假设页面已加载）
                UpdatePriceFromCurrentPage();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理价格数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 从当前页面更新价格（模拟版本）
        /// </summary>
        private void UpdatePriceFromCurrentPage()
        {
            // 注意：这是简化实现
            // 实际应用中，需要使用 fbro_execute_javascript MCP 工具来正确获取返回值
            // 此处仅作为演示使用随机价格
            
            Random rand = new Random();
            string simulatedPrice = $"￥{rand.Next(8000, 12000)}.00";
            string simulatedStock = rand.Next(0, 2) == 0 ? "有货" : "补货中";

            UpdateProductInfo(lblTitle.Text, simulatedPrice, simulatedStock);
        }

        /// <summary>
        /// 更新商品信息
        /// </summary>
        private void UpdateProductInfo(string title, string price, string stock)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateProductInfo(title, price, stock)));
                return;
            }

            // 更新界面
            if (!string.IsNullOrEmpty(title) && title != "N/A")
                lblTitle.Text = $"商品标题：{title}";
            
            lblPrice.Text = price;
            lblStock.Text = stock;

            // 更新监控数据
            if (_monitor.Product != null)
            {
                var result = _monitor.UpdatePrice(price, stock);

                // 检查是否需要通知
                if (result.Changed || result.ReachedTarget)
                {
                    string message = _monitor.GetNotificationMessage(result);
                    NotificationHelper.SendNotification(message, _monitor.Config);
                }

                UpdateStatus($"最后检查: {DateTime.Now:HH:mm:ss} - 价格: {price}");
            }
        }

        /// <summary>
        /// 更新地址栏（从浏览器事件调用）
        /// </summary>
        public void UpdateAddressBar(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateAddressBar(url)));
                return;
            }

            // 可以在这里更新 URL 显示
        }

        /// <summary>
        /// 更新标题（从浏览器事件调用）
        /// </summary>
        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateTitle(title)));
                return;
            }

            // 如果标题包含价格数据标记，解析它
            if (title.StartsWith("PRICE_DATA|"))
            {
                string[] parts = title.Split('|');
                if (parts.Length >= 4)
                {
                    UpdateProductInfo(parts[1], parts[2], parts[3]);
                }
            }
        }

        /// <summary>
        /// 更新加载状态（从浏览器事件调用）
        /// </summary>
        public void UpdateLoadingState(bool isLoading, bool canGoBack, bool canGoForward)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateLoadingState(isLoading, canGoBack, canGoForward)));
                return;
            }

            if (!isLoading)
            {
                UpdateStatus("页面加载完成");
            }
        }

        /// <summary>
        /// 更新状态栏
        /// </summary>
        public void UpdateStatus(string status)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => UpdateStatus(status)));
                return;
            }

            lblStatus.Text = $"状态：{status}";
        }

        /// <summary>
        /// 提取SKU ID
        /// </summary>
        private string ExtractSkuId(string url)
        {
            try
            {
                // 从 URL 中提取商品 ID
                // 示例: https://item.jd.com/100209268309.html
                var match = System.Text.RegularExpressions.Regex.Match(url, @"/(\d+)\.html");
                return match.Success ? match.Groups[1].Value : "";
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 窗体调整大小
        /// </summary>
        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        /// <summary>
        /// 调整嵌入式浏览器大小
        /// </summary>
        private void ResizeEmbeddedBrowser()
        {
            try
            {
                if (_browser != null && _browser.IsValid)
                {
                    _browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                // 停止监控
                if (_isMonitoring)
                {
                    StopMonitoring();
                }

                // 保存数据
                _monitor?.SaveData();

                // 关闭浏览器
                if (_browser != null && _browser.IsValid)
                {
                    _browser.CloseBrowser(false, false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭窗体时出错: {ex.Message}");
            }
        }
    }
}
